// 定义定时器
// 启动定时器
window.requestAnimationFrame = window.requestAnimationFrame || function (fn) {
    return setTimeout(() => {
        fn
    }, 1000 / 60);
}
// 停止定时器
window.cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;
// 定义全局变量
var wrap = document.getElementById("wrap");
var score = document.getElementById("score");
var resetStart = document.getElementById("reset_start");
var level = document.getElementById("level");
var map = document.getElementById("map");
var biuAll = document.getElementById("biu_all");
var biuAllChildren = biuAll.children;
var resetStartChildren = resetStart.children;
var wrapOffsetTop = wrap.offsetTop;
var wrapOffsetLeft = wrap.offsetLeft;
// 初始化
init()
// 初始化选择难度界面的点击事件
function init() {
    // 难度选择
    var p_list = level.getElementsByTagName("p");
    for (let i = 0, length = p_list.length; i < length; i++) {
        (function () {
            p_list[i].onclick = function (e) {
                e = e || window.event;
                // 鼠标的位置减去wrap的位置，即获得鼠标距离map边缘的位置
                startGame(i, {
                    x: e.clientX - wrapOffsetLeft,
                    y: e.clientY - wrapOffsetTop
                })
                // 第一个实参为背景序号 ，第二个实参为存储着鼠标距离 map 边缘距离的对象
            }
        })(i)
    }
    // reset_start 按钮
    resetStartChildren[2].onclick = function (e) {
        //停止背景滚动
        cancelAnimationFrame(map.bgTimer);
        resetStart.style.display = "none";
        level.style.display = "block";
        score.innerHTML = 0;
        map.innerHTML = "<div id='biu_all'></div>";
        biuAll = document.getElementById("biu_all");
        biuAllChildren = biuAll.children;
    }
}
// 开始游戏
// 传递游戏背景信息level，生成敌军位置pos
function startGame(level, pos) {
    // 清除游戏界面
    clearMap();
    // 执行背景相关的操作
    mapBg(level);
    // 执行创建我军
    var myPlane = myselfPlane(level, pos)
    // 执行创建敌军
    enemy(level, myPlane);
    // 得分清零
    wrap.score = 0;
}
// 清除游戏界面
function clearMap() {
    score.style.display = "block";
    // 隐藏选择关卡选择框
    level.style.display = "none";
}
// map背景的选择和运动
function mapBg(level) {
    map.style.backgroundImage = "url('./img/bg_" + (level + 1) + ".jpg')";
    (function moveBg() {
        // 为 map 添加属性，通过属性的存在，实现背景图的移动
        // 利用的是背景平铺的特性
        map.bgPositionY = map.bgPositionY || 0;
        map.bgPositionY++;
        map.style.backgroundPositionY = map.bgPositionY + 'px';
        map.bgTimer = requestAnimationFrame(moveBg);
    })()
}
// 创建我军
function myselfPlane(level, pos) {
    // 创建我军的图片
    var myselfImg = new Image();
    myselfImg.src = "./img/plane_1.png";
    myselfImg.width = 70;
    myselfImg.height = 70;
    myselfImg.className = "plane";
    myselfImg.style.left = pos.x - myselfImg.width / 2 + "px";
    myselfImg.style.top = pos.y - myselfImg.height / 2 + "px";
    map.appendChild(myselfImg)
    // 边界值
    var leftMin = -myselfImg.width / 2;
    var leftMax = map.clientWidth - myselfImg.width / 2;
    var topMin = 0;
    var topMax = map.clientHeight - myselfImg.height / 2;
    // onmousemove事件
    document.onmousemove = function (e) {
        e = e || window.event;
        // 获取飞机的实时坐标，并限制边界值
        var left = e.clientX - wrapOffsetLeft - myselfImg.width / 2;
        var top = e.clientY - wrapOffsetTop - myselfImg.height / 2;
        // 当鼠标的坐标小于最小边界值时，选取最小边界值
        // 当鼠标的坐标大于于最大边界值时，选取最大边界值
        left = Math.max(leftMin, left);
        left = Math.min(leftMax, left);
        top = Math.max(topMin, top);
        top = Math.min(topMax, top);
        myselfImg.style.left = left + "px";
        myselfImg.style.top = top + "px";
    }
    // 调用子弹函数
    fire(myselfImg, level);
    return myselfImg;
}
// 我军子弹
function fire(myselfImg, level) {
    wrap.biuInterval = setInterval(() => {
        if (wrap.score >= 500) {
            createBiu(true, -1);
            createBiu(true, 1);
        } else {
            createBiu();
        }
    }, [200, 150, 100, 15][level]);
    // 创建子弹
    function createBiu(index, d) {
        var biu = new Image();
        biu.src = "./img/fire.png";
        biu.width = 30;
        biu.height = 30;
        biu.className = "biu";
        // 设置子弹的位置
        var left = myselfImg.offsetLeft + myselfImg.width / 2 - biu.width / 2;
        var top = myselfImg.offsetTop - biu.height + 5;
        if (index) {
            left += biu.width * d;
        }
        biu.style.left = left + "px";
        biu.style.top = top + "px";
        biuAll.appendChild(biu);
        // 子弹运动
        function biuMove() {
            if (biu.parentNode) {
                // 设置子弹位置
                var top = biu.offsetTop - 20;
                if (top < -biu.height) {
                    biuAll.removeChild(biu);
                } else {
                    biu.style.top = top + "px";
                    requestAnimationFrame(biuMove);
                }
            }
        }
        // 执行子弹运动
        setTimeout(function () {
            requestAnimationFrame(biuMove);
        }, 50);
    }
}
// 创建敌军
function enemy(level, myPlane) {
    var width = map.clientWidth;
    var height = map.clientHeight;
    // 敌军下落的速度
    var speed = [5, 6, 8, 8][level];
    var num = 1;
    wrap.enemyInterval = setInterval(() => {
        var index = num % 30 ? 1 : 0;
        // 生成敌军
        var enemy = new Image();
        enemy.index = index;
        enemy.HP = [20, 1][index];
        enemy.speed = speed + (Math.random() * 0.6 - 0.3) * speed;
        enemy.speed *= index ? 1 : 0.5;
        enemy.src = "./img/enemy_" + ["big", "small"][index] + ".png";
        enemy.className = "enemy";
        enemy.width = [104, 54][index];
        enemy.height = [80, 40][index];
        enemy.style.left = Math.random() * width - enemy.width / 2 + 'px';
        enemy.style.top = -enemy.height + 'px';
        map.appendChild(enemy);
        num++;
        // 敌军运动
        function enemyMove() {
            if (enemy.parentNode) {
                var top = enemy.offsetTop;
                top += enemy.speed;
                if (top >= height) {
                    // 漏掉的飞机减分
                    wrap.score--;
                    score.innerHTML = wrap.score;
                    map.removeChild(enemy);
                } else {
                    enemy.style.top = top + "px";
                    // 子弹碰撞检测
                    for (var i = biuAllChildren.length - 1; i >= 0; i--) {
                        var biuObj = biuAllChildren[i];
                        if (coll(enemy, biuObj)) {
                            // 移除子弹
                            biuAll.removeChild(biuObj);
                            enemy.HP--;
                            if (!enemy.HP) {
                                // 打掉飞机加分
                                wrap.score += enemy.index ? 2 : 20;
                                score.innerHTML = wrap.score;
                                // 敌军爆炸效果
                                boom(enemy.offsetLeft, enemy.offsetTop, enemy.width, enemy.height, index ? 0 : 2);
                                // 移除敌军
                                map.removeChild(enemy);
                                return;
                            }
                        }
                    }
                    // 我军碰撞检测
                    if (myPlane.parentNode && coll(enemy, myPlane)) {
                        // 敌军爆炸效果
                        boom(enemy.offsetLeft, enemy.offsetTop, enemy.width, enemy.height, index ? 0 : 2);
                        // 我军爆炸效果
                        boom(myPlane.offsetLeft, myPlane.offsetTop, myPlane.width, myPlane.height, 1);
                        // 移除敌军
                        map.removeChild(enemy);
                        // 移除我军
                        map.removeChild(myPlane);
                        GameOver();
                        return;
                    }
                    // 调用敌军移动方法
                    requestAnimationFrame(enemyMove);
                }
            }
        }
        requestAnimationFrame(enemyMove);
    }, [380, 200, 120, 40][level]);
}
// 碰撞检测
function coll(obj1, obj2) {
    var T1 = obj1.offsetTop,
        B1 = T1 + obj1.clientHeight,
        L1 = obj1.offsetLeft,
        R1 = L1 + obj1.clientWidth;
    var T2 = obj2.offsetTop,
        B2 = T2 + obj2.clientHeight,
        L2 = obj2.offsetLeft,
        R2 = L2 + obj2.clientWidth;
    return !(B1 < T2 || R1 < L2 || T1 > B2 || L1 > R2);
}
// 爆炸效果
function boom(l, t, w, h, i) {
    var booms = new Image();
    booms.src = "img/" + ["boom_small", "plane_1", "boom_big"][i] + ".png";
    // 添加爆炸闪烁动画
    booms.className = 'boom' + ["", "2", ""][i];
    booms.width = w;
    booms.height = h;
    booms.style.left = l + "px";
    booms.style.top = t + 'px';
    map.appendChild(booms);
    setTimeout(function () {
        booms.parentNode && map.removeChild(booms);
    }, [1200, 2500, 1200][i]);
}
//游戏结束
function GameOver() {
    // 清除移动事件
    document.onmousemove = null;
    // 不再产生新子弹
    clearInterval(wrap.biuInterval);
    // 不再产生新敌军
    clearInterval(wrap.enemyInterval);
    restart();
}
//结算+重新开始
function restart() {
    score.style.display = "none";
    var s = wrap.score;
    var honor;
    if (s < -300) {
        honor = "闪避+MAX！！！";
    } else if (s < 10) {
        honor = "菜得…算了我不想说了…";
    } else if (s < 30) {
        honor = "抠脚侠！";
    } else if (s < 100) {
        honor = "初级飞机大师";
    } else if (s < 200) {
        honor = "渐入佳境";
    } else if (s < 500) {
        honor = "中级飞机大师";
    } else if (s < 1000) {
        honor = "高级飞机大师";
    } else if (s < 5000) {
        honor = "终极飞机大师";
    } else {
        honor = "孤独求败！";
    }
    resetStart.style.display = "flex";
    resetStartChildren[0].children[0].innerHTML = s;
    resetStartChildren[1].children[0].innerHTML = honor;
}